import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';
import tool from "@/utils/tool";

export const useSubsystemStore = defineStore('subsystem', () => {
  const subsystem = ref(null);
  const loading = ref(false);

  const getInfo = () => {
    return subsystem.value;
  };

  const getSubsystem = async() => {
    if (subsystem.value != null) {
      return subsystem.value;
    } else {
      return await loadSubsystem();
    }
  };

  const loadSubsystem = async() => {
    if (subsystem.value != null) {
      loading.value = false;
      return subsystem.value;
    }

    if (loading.value) {
      await sleep(100);
      return await loadSubsystem();
    }

    loading.value = true;
    if (subsystem.value != null) {
      loading.value = false;
      return subsystem.value;
    } else {
      const urlParams = new URLSearchParams(window.location.search);
      const subsystemId = urlParams.get('subsystemId');

      if (!subsystemId) {
        window.location.href = tool.getBaseUrl() + "/choose.html";
        return null;
      }
      
      const res = await api.post('/business/subsystem/' + subsystemId).catch(() => {
        loading.value = false;
      });
      loading.value = false;
      if (res.code === '1') {
        subsystem.value = res.data;
        return subsystem.value;
      }
    }
  };

  const sleep = async(d) => {
    return new Promise((resolve) => setTimeout(resolve, d));
  };

  return {
    getInfo,
    getSubsystem
  };
});
